import React, { useEffect, useRef } from 'react';
import styles from './index.less';
interface Props {}
const DragList: React.FC<Props> = (props) => {
  const {} = props;
  const dragRef = useRef<any>();
  useEffect(() => {
    let selfNode;
    dragRef.current.ondragstart = (e) => {
      e.dataTransfer.effectAllowed = 'move';
      e.dataTransfer.setData('Text', e.target.id);

      console.log(e);
      setTimeout(() => {
        e.target.style.background = 'transparent';
        e.target.style.color = 'transparent';
        e.target.style.border = '1px dashed #ccc';
      }, 0);
      selfNode = e.target;
    };
    dragRef.current.ondragover = (e) => {
      e.preventDefault();
    };
    dragRef.current.ondragenter = (e) => {
      e.preventDefault();
      console.log('enter', e);
      if (e.target === dragRef.current || e.target === selfNode) {
        return;
      }
      const children = Array.from(dragRef.current.children);
      const selfIndex = children.indexOf(selfNode);
      const targetIndex = children.indexOf(e.target);
      console.log(selfNode, e.target);
      if (selfIndex < targetIndex) {
        dragRef.current.insertBefore(selfNode, e.target.nextElementSibling);
      } else {
        dragRef.current.insertBefore(selfNode, e.target);
      }
    };
    dragRef.current.ondragend = (e) => {
      selfNode.style.color = '';
      selfNode.style.border = 'none';
      selfNode.style.background = '';
    };
  }, []);
  const goods = [
    {
      id: 'apple',
      draggable: true,
      name: '苹果',
    },
    {
      id: 'banana',
      draggable: true,
      name: '香蕉',
    },
    {
      id: 'ss',
      draggable: true,
      name: '西瓜',
    },
  ];

  return (
    <div className={styles.container} ref={dragRef}>
      {goods.map((item, index) => {
        return (
          <div id={item.id} draggable={item.draggable} className={styles.item}>
            {item.name}
          </div>
        );
      })}
    </div>
  );
};
export default DragList;
